package com.mrdeer.common.tools;

import cn.hutool.core.util.StrUtil;
import cn.hutool.db.PageResult;
import com.mrdeer.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class PageUtil {
    private final static String[] KEYWORDS = {"master", "truncate", "insert", "select",
            "delete", "update", "declare", "alter", "drop", "sleep"};

    private PageUtil() {
        throw new BusinessException("Utility class");
    }

    public static <T> List<T> list2Page(PageResult<T> page, List<T> list) {
        return null;
    }

    /**
     * 驼峰法转下划线
     *
     * @param str
     * @return
     */
    public static String camel2Underline(String str) {
        if (StrUtil.isBlank(str)) {
            return "";
        }
        if (str.length() == 1) {
            return str.toLowerCase();
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i < str.length(); i++) {
            if (Character.isUpperCase(str.charAt(i))) {
                sb.append("_" + Character.toLowerCase(str.charAt(i)));
            } else {
                sb.append(str.charAt(i));
            }
        }
        return (str.charAt(0) + sb.toString()).toLowerCase();
    }

    /**
     * 防止Mybatis-plus order by 注入
     *
     * @param param
     */
    public static void SQLInject(String param) {
        if (StrUtil.isBlank(param)) {
            return;
        }
        //转换成小写
        param = param.toLowerCase();
        //判断是否包含非法字符
        for (String keyword : KEYWORDS) {
            if (param.contains(keyword)) {
                throw new BusinessException(param + "包含非法字符");
            }
        }
    }
}
